import { getStatisticBrief } from '../../../api/index'
import { formatTimeTwo } from '../../../utils/util'
import * as echarts from '../../components/ec-canvas/echarts'
let userData = {
  xData: [],
  accessUserData: [],
  followUserData: []
}
let orderData = {
  xData: [],
  series: []
}
let hybridData = {
  xData: [],
  materialData: [],
  caseData: []
}

function setUserOption (chart) {
  const option = {
    color: ['#FF708B'],
    tooltip: {
      trigger: 'axis',
      axisPointer: {            // 坐标轴指示器，坐标轴触发有效
        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
      },
      formatter: function (data) {
        let text = data[0].name + '\n', val;
        for(let i = 0; i < data.length; i++) {
          text += data[i].marker + data[i].seriesName  + ': '+ data[i].value+'\n';
        }
        return text;
      },
      confine: true
    },
    grid: {
      left: 20,
      right: 20,
      bottom: 15,
      top: 40,
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: userData.xData
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '访问用户',
        data: userData.accessUserData,
        type: 'line',
        smooth: true,
        lineStyle: {
          normal: {
            color: '#8676FF'
          }
        },
        itemStyle: {
          normal: {
            color: '#8676FF'
          }
        }
      },
      {
        name: '新增用户',
        data: userData.followUserData,
        type: 'line',
        smooth: true,
        lineStyle: {
          normal: {
            color: '#FF708B'
          }
        },
        itemStyle: {
          normal: {
            color: '#FF708B'
          }
        }
      }
    ]
  }
  chart.setOption(option)
}

function setOrderOption (chart) {
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {            // 坐标轴指示器，坐标轴触发有效
        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
      },
      formatter: function (data) {
        let text = data[0].name + '\n', val;
        for(let i = 0; i < data.length; i++) {
          text += data[i].marker + data[i].seriesName  + ': '+ data[i].value+'\n';
        }
        return text;
      },
      confine: true
    },
    grid: {
      left: 20,
      right: 20,
      bottom: 15,
      top: 40,
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: orderData.xData
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      name: '样品订单数',
      data: orderData.series,
      type: 'line',
      smooth: true,
      lineStyle: {
        normal: {
          color: '#FF708B'
        }
      },
      itemStyle: {
        normal: {
          color: '#FF708B'
        }
      }
    }]
  }
  chart.setOption(option)
}

function setCaseOption (chart) {
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {            // 坐标轴指示器，坐标轴触发有效
        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
      },
      formatter: function (data) {
        let text = data[0].name + '\n', val;
        for(let i = 0; i < data.length; i++) {
          text += data[i].marker + data[i].seriesName  + ': '+ data[i].value+'\n';
        }
        return text;
      },
      confine: true
    },
    grid: {
      left: 20,
      right: 20,
      bottom: 15,
      top: 40,
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: hybridData.xData
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '新增材料数',
        data: hybridData.materialData,
        type: 'line',
        smooth: true,
        lineStyle: {
          normal: {
            color: '#8676FF'
          }
        },
        itemStyle: {
          normal: {
            color: '#8676FF'
          }
        }
      },
      {
        name: '新增案例数',
        data: hybridData.caseData,
        type: 'line',
        smooth: true,
        lineStyle: {
          normal: {
            color: '#FF708B'
          }
        },
        itemStyle: {
          normal: {
            color: '#FF708B'
          }
        }
      }
    ]
  }
  chart.setOption(option)
}

Page({
  data: {
    ecUser: {
      lazyLoad: true
    },
    ecOrder: {
      lazyLoad: true
    },
    ecCase: {
      lazyLoad: true
    },
    detail: {},
    showDatePop: false,
    type: 1,
    typeStr: '日统计',
    showCalendar: false,
    startDateStr: '',
    endDateStr: '',
    timeStr: formatTimeTwo(new Date().getTime(), 'Y-M-D')
  },
  selectDate () {
    this.setData({ showDatePop: true })
  },
  closeSelectDate () {
    this.setData({ showDatePop: false })
  },
  async changeType ({ detail }) {
    this.setData({ type: detail.value, typeStr: detail.label, showDatePop: false })
    if (detail.value !== 4) {
      await this.setTime()
      await this.getDetail()
      this.initChart()
    }
  },
  selectTime () {
    this.setData({ showCalendar: true })
  },
  closeCalendar () {
    this.setData({ showCalendar: false })
  },
  async changeTime ({ detail }) {
    this.setData({ startDateStr: detail[0], endDateStr: detail[1], showCalendar: false })
    await this.getDetail()
    wx.$pro.nextTick(() => {
      this.initChart()
    })
  },
  initChart () {
    this.ecUserComponent = this.selectComponent('#mychart-user-bar')
    this.ecOrderComponent = this.selectComponent('#mychart-order-bar')
    this.ecCaseComponent = this.selectComponent('#mychart-case-bar')
    console.log(this.ecUserComponent)
    this.ecUserComponent.init((canvas, width, height, dpr) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      setUserOption(chart)

      // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
      this.chart = chart

      this.setData({
        isLoaded: true,
        isDisposed: false
      })

      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return chart
    })
    this.ecOrderComponent.init((canvas, width, height, dpr) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      setOrderOption(chart)

      // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
      this.chart = chart

      this.setData({
        isLoaded: true,
        isDisposed: false
      })

      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return chart
    })
    this.ecCaseComponent.init((canvas, width, height, dpr) => {
      // 获取组件的 canvas、width、height 后的回调函数
      // 在这里初始化图表
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      setCaseOption(chart)

      // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
      this.chart = chart

      // this.setData({
      //   isLoaded: true,
      //   isDisposed: false
      // })

      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return chart
    })
  },
  setTime () {
    if (this.data.type === 1) {
      this.setData({ timeStr: formatTimeTwo(new Date().getTime(), 'Y-M-D') })
    } else if (this.data.type === 2) {
      let startTime = formatTimeTwo(new Date().getTime() - (7*24*60*60*1000), 'Y-M-D')
      let endTime = '今日'
      this.setData({ timeStr: `${startTime} 至 ${endTime}` })
    } else if (this.data.type === 3) {
      this.setData({ timeStr: formatTimeTwo(new Date().getTime(), 'Y-M') })
    }
  },
  async getDetail () {
    try {
      let query = { type: this.data.type }
      if (query.type === 3) {
        query.monthStr = formatTimeTwo(new Date().getTime(), 'Y-M')
      } else if (query.type === 4) {
        query.startDateStr = this.data.startDateStr
        query.endDateStr = this.data.endDateStr
      }
      const { ResultSet } = await getStatisticBrief({ ...query })
      let xData = []
      let accessUserData = []
      let followUserData = []
      ResultSet.userData.accessUserData.forEach(item => {
        xData.push(item.time)
        accessUserData.push(item.count)
      })
      ResultSet.userData.followUserData.forEach(item => {
        followUserData.push(item.count)
      })
      userData.xData = xData
      userData.accessUserData = accessUserData
      userData.followUserData = followUserData
      if (ResultSet.userData.orderData.length) {
        let xData = []
        let series = []
        ResultSet.userData.orderData.forEach(item => {
          xData.push(item.time)
          series.push(item.count)
        })
        orderData.xData = xData
        orderData.series = series
      }
      if (ResultSet.userData.materialData.length) {
        let xData = []
        let materialData = []
        ResultSet.userData.materialData.forEach(item => {
          xData.push(item.time)
          materialData.push(item.count)
        })
        hybridData.xData = xData
        hybridData.materialData = materialData
      }
      if (ResultSet.userData.caseData.length) {
        let caseData = []
        ResultSet.userData.caseData.forEach(item => {
          caseData.push(item.count)
        })
        hybridData.caseData = caseData
      }
      console.log(hybridData)
      this.setData({ detail: ResultSet.userData })
    } catch (err) {
      console.log(err)
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  onLoad () {
    this.getDetail()
  }
})